﻿// 文件名：函数指针
// 创建时间：2021/6/21/星期一 21:36:21

#include <iostream>
using namespace std;

//函数指针示例
double betsy(int);
double pam(int);
void estimate(int lines, double(*pf)(int));
void fun_ptr()
{
	int code;
	cout << "How many lines of code do you need? ";
	cin >> code;
	cout << "Here's Betsy's estimate:\n";
	estimate(code, betsy);
	cout << "Here's Pam's estimate:\n";
	estimate(code, pam);
}
double betsy(int lns)
{
	return 0.05*lns;
}
double pam(int lns)
{
	return 0.03*lns + 0.0004*lns*lns;
}
void estimate(int lines, double(*pf)(int))//传入函数的指针，而不是某个特定函数
{
	cout << lines << " lines will take ";
	cout << (*pf)(lines) << " hour(s)\n";
}


//定义三个空的函数
const double* f1(const double arr[], int n) 
{
	cout << "调用函数f1\n";
	const double a = 1.0;
	return &a;
}
const double* f2(const double[], int) 
{
	cout << "调用函数f2\n";
	const double a = 1.0;
	return &a;
}
const double* f3(const double*, int)
{
	cout << "调用函数f3\n";
	const double a = 1.0;
	return &a;
}

int main()
{



	//函数指针示例程序调用
	//fun_ptr();

	//函数指针高阶
	double arr[2];
	int n = 0;
	const double* (*p1)(const double*, int) = f1;//p1 = 函数指针
	auto p2 = f2; //自动类型推断
	(*p1)(arr, n);//通过指针调用函数f1,两种方式都支持
	p2(arr, n);   //通过指针调用函数f2
	cout << "p2(arr, n) = " << p2(arr, n) << endl;//函数的返回值是一个指针
	cout << "*p2(arr, n) = " << *p2(arr, n) << endl;//对指针解引用

	//函数指针数组
	const double* (*pa[3])(const double*, int) = {f1,f2,f3};
	auto pb = pa; //pa和pb都是指向函数指针的指针
	const double* px = pa[0](arr, n); //pa[i]指向fi
	const double* py = (*pb[1])(arr, n);//*pb[0] = *p1 = f1
	cout << "*px = " << *px << " and " << "* pa[0](arr, n) = " << *pa[0](arr, n) << endl;
	cout << "*py = " << *py << " and " << "* (*pb[1])(arr, n) = " << *(*pb[1])(arr, n) << endl;

	//再创建一个指向整个数组的指针,(*pd) = pa
	auto pc = &pa;
	//*pd[3]是包含三个指针的数组
	//(*pd)[3]是一个指向包含三个元素的指针
	const double* (*(*pd)[3])(const double*, int);
	pd = &pa;
	const double* pxx = (*pd)[1](arr, n);
	const double* pyy = (*(*pd)[2])(arr, n);
	cout << "*pxx = " << *((*pd)[1](arr, n)) << endl;
	cout << "*pyy = " << *((*(*pd)[2])(arr, n)) << endl;

	system("pause");
	return 0;
}